#ifndef DB_H
#define DB_H 1

#include <sys/param.h>
#include <stdarg.h>

#include "main.h"
#include "array.h"

#define DB_ERR_OK		0
#define DB_ERR_ARG		1
#define DB_ERR_NOSTMT		2
#define DB_ERR_THRD		3
#define DB_ERR_MORE		4

#define DB_ARGLEN		MAXPATHLEN


typedef enum __ncattr__ db_datatype {
  db_nulltype = 0,
  db_uint,
  db_int,
  db_str,
  db_char,
  db_bin
} db_datatype_t;

typedef struct __ncattr__ db_stmt {
  const void *bind_value;
  int len;
  db_datatype_t dtype;
} db_stmt_t;

typedef struct __ncattr__ db_result {
  const void *data;
  int len;
  struct db_result *nextcol;
  struct db_result *nextrow;
} db_result_t;

extern const char db_err_init_s[];
extern const char db_err_create_s[];
extern const char db_err_close_s[];

int
db_set_arg(const char *__arg);

char *
db_get_arg(void);

db_result_t *
db_create_result(void);

void
db_free_results(db_result_t *first_elem);

db_stmt_t *
db_init_stmt(const db_datatype_t dtypes[], int len);

void
db_bind_val(db_stmt_t *st, int *idx, const void *data, int len);

void
db_bind_str(db_stmt_t *st, int *idx, const char *str, int len);

void
db_bind_int(db_stmt_t *st, int *idx, const long int *num);

void
db_bind_chr(db_stmt_t *st, int *idx, const char *c);

void
db_free_stmt(void *__db_st, db_stmt_t *st, int len);

#define CHECK_RET(cmd, ret) if ( (ret = cmd) != DB_ERR_OK) { E("db: " #cmd " returned %d", ret); }
#define DB_EXEC(hndl, stmt, result, sql, db_stmt, dtypes) db_exec(hndl, stmt, result, sql, db_stmt, sizeof(dtypes)/sizeof(dtypes[0]))
#define DB_STMT(dtypes) db_init_stmt(dtypes, sizeof(dtypes)/sizeof(dtypes[0]));
#define DB_STMT2 db_init_stmt(NULL, 0);
#define DB_STMTFREE(dbstmt, stmt, dtypes) db_free_stmt(dbstmt, stmt, sizeof(dtypes)/sizeof(dtypes[0]));
#define DB_STMTFREE2(dbstmt, stmt) db_free_stmt(dbstmt, stmt, 0);
#define DB_RESULT(result1_str, result2_str, fmt1, fmt2, db_result); db_result_t *tmp = db_result; while (tmp) { if (tmp->data) { } }

#undef db_parse_arg
#undef db_preinit
#undef db_shutdown
#undef db_init
#undef db_close
#undef db_exec_simple
#undef db_vexec_simple
#undef db_exec
#undef db_finish

#include "db_sqlite3.h"

#endif
